import React, {useEffect, useState} from 'react';
import {
  Card,
  CardContent,
  CardHeader,
  CircularProgress,
  Grid,
  IconButton,
  TextField,
  Tooltip,
  Typography
} from "@material-ui/core";
import {useDispatch, useSelector} from "react-redux";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import ModalMessage from "../../Common/Modal/ModalMessage";
import {setLeftDrawerMenuIndex} from "../../../../../redux/reducers/commonSettings";
import {useHistory} from "react-router-dom";
import {
  addNewQuestionAndIndicators,
  confirmQuestionName,
  getQuestionNameValidation,
  resetSession,
  saveQuestionAndIndicators
} from "../../../../../redux/reducers/gqiEditor";
import {faExclamation} from "@fortawesome/free-solid-svg-icons";
import Avatar from "@material-ui/core/Avatar";
import VisualizationPreview from "./VisualizationPreview/VisualizationPreview";
import {
  indicatorResponseToQueryWrapper,
  saveQuestionAndIndicatorWrapper
} from "../../../../../ruleEngine/rulesGenerator";
import Backend from "../../../../Backend/Backend";
import parse from "html-react-parser";
import {countWords, scrollToTop} from "../../../../../assets/functions/functions";
import Divider from "@material-ui/core/Divider";
import SnackbarMessage from "../../Common/Snackbar/SnackbarMessage";
import Button from "@material-ui/core/Button";
import SaveIcon from '@material-ui/icons/Save';
import DoneIcon from "@material-ui/icons/Done";
import EditIcon from "@material-ui/icons/Edit";
import {makeStyles} from "@material-ui/core/styles";

const useStyles = makeStyles((theme) => ({
  gutter: {
    margin: theme.spacing(2, 0, 2, 0)
  },
  gutterBottom: {
    margin: theme.spacing(0, 0, 2, 0)
  },
  buttonSpacing: {
    marginRight: theme.spacing(1)
  },
}));

export default function Visualize(props) {
  // Props
  const {handleStepBackward, dashboardModal, setDashboardModal, classes} = props;

  // Constants from redux store
  const selectedGoal = useSelector((state) => state.gqiEditor.selectedData.goal);
  const questionSelected = useSelector((state) => state.gqiEditor.selectedData.question);
  const questionAvailable = useSelector(state => state.gqiEditor.fetchedData.questionAvailable);
  const indicatorsSelected = useSelector((state) => state.gqiEditor.selectedData.indicators);
  const questionConfirmed = useSelector(state => state.gqiEditor.common.questionConfirmed);

  // Local constants
  const history = useHistory();
  const dispatch = useDispatch();
  const styles = useStyles();
  const [errorInput, setErrorInput] = useState(false);
  const [selection, setSelection] = useState({
    questionName: questionSelected ? questionSelected.name : "",
    errorMessage: "",
  });
  const [codeFetched, setCodeFetched] = useState(false);
  const [visualizationData, setVisualizationData] = useState([]);

  useEffect(() => {
    scrollToTop();
    handleRequestVisualizationCodes(indicatorsSelected);
  }, [indicatorsSelected])

  const handleSaving = () => {
    setDashboardModal(!dashboardModal);
    dispatch(saveQuestionAndIndicators(saveQuestionAndIndicatorWrapper(questionSelected, selectedGoal, indicatorsSelected)));
  }


  const handleRequestVisualizationCodes = async (indicatorData) => {
    let indicatorsWithVizWrapper = [];
    try {
      for (const indicator of indicatorData) {
        let newIndicatorData = {};
        const vizQuery = indicatorResponseToQueryWrapper(indicator);
        await Backend.post("/AnalyticsEngine/GetIndicatorPreview", vizQuery)
          .then(response => {
            const unescapedVizCode = decodeURIComponent(response.data.visualizationCode);
            let displayData = parse(unescapedVizCode);
            newIndicatorData["indicator"] = indicator;
            newIndicatorData["displayCode"] = displayData;
            newIndicatorData["scriptData"] = displayData[1].props.dangerouslySetInnerHTML.__html;
          }, (error) => {
            console.log(error);
          })
        indicatorsWithVizWrapper.push(newIndicatorData);
      }
      setVisualizationData(indicatorsWithVizWrapper)
      setCodeFetched(true);
    } catch (error) {
      console.log(error)
    }
  }

  const handleBackToDashboard = () => {
    dispatch(addNewQuestionAndIndicators());
    dispatch(setLeftDrawerMenuIndex(1));
    history.push('/dashboard');
    dispatch(resetSession());
  }

  const handleSetQuestionName = (e) => {
    const {name, value} = e.target;
    setSelection({
      ...selection,
      [name]: value
    });
    if (errorInput)
      setErrorInput(false)
  };

  const handleQuestionNameUpdated = (confirmation) => {
    if (selection.questionName) {
      if (countWords(selection.questionName) > 3) {
        dispatch(getQuestionNameValidation(selection.questionName));
        dispatch(confirmQuestionName(selection.questionName, confirmation));
      } else {
        setSelection({
          ...selection,
          errorMessage: "Name is too short, try again with at least four words to describe the question."
        });
        setErrorInput(!errorInput);
      }
    } else {
      setSelection({
        ...selection,
        errorMessage: "A question is required!"
      });
      setErrorInput(!errorInput);
    }
  }

  return (
    <>
      <Grid item lg={9}>
        <Card elevation={5} style={{borderRadius: 16}}>
          <Grid container>
            <Grid item xs>
              <CardHeader
                avatar={questionConfirmed && !questionAvailable ? (
                  <Tooltip arrow placement="left"
                           title="This question is not available">
                    <Avatar className={classes.avatarError}>
                      <Typography variant="h5">
                        <FontAwesomeIcon icon={faExclamation} size="sm"/>
                      </Typography>
                    </Avatar>
                  </Tooltip>
                ) : <></>}
                title={
                  questionConfirmed ? (
                    <Grid container alignItems="center">
                      <Grid item>
                        <Grid container direction="column">
                          <Typography variant="overline">{selectedGoal.name}</Typography>
                          <Typography variant="h5">{selection.questionName}</Typography>
                          <Typography variant="overline">#Indicators: {indicatorsSelected.length}</Typography>
                        </Grid>
                      </Grid>
                      <Grid item className={styles.buttonSpacing}>
                        <Tooltip arrow placement="bottom"
                                 title="Edit question">
                          <IconButton color="inherit" onClick={() => handleQuestionNameUpdated(false)}>
                            <EditIcon/>
                          </IconButton>
                          {/*<Button variant="outlined" startIcon={<EditIcon/>}*/}
                          {/*        onClick={() => handleQuestionNameUpdated(false)}>*/}
                          {/*  Edit*/}
                          {/*</Button>*/}
                        </Tooltip>
                      </Grid>
                    </Grid>
                  ) : (
                    <Grid container direction="column">
                      <Typography variant="overline">{selectedGoal.name}</Typography>
                      <form onSubmit={() => handleQuestionNameUpdated(true)}>
                        <Grid container alignItems="center">
                          <Grid item xs style={{paddingRight: "16px"}}>
                            <TextField
                              autoFocus
                              id="questionName"
                              name="questionName"
                              required
                              margin="dense"
                              value={selection.questionName}
                              onChange={(e) => handleSetQuestionName(e)}
                              placeholder="Name the question e.g. How active are my students?"
                              fullWidth
                              error={errorInput}
                              helperText={errorInput ? selection.errorMessage : ""}
                            />
                          </Grid>
                          <Grid item>
                            <Tooltip arrow placement="bottom"
                                     title="Confirm indicator name">
                              <IconButton color="inherit" type="submit">
                                <DoneIcon/>
                              </IconButton>
                              {/*<Button variant="outlined" endIcon={<DoneIcon/>} type="submit">*/}
                              {/*  Confirm*/}
                              {/*</Button>*/}
                            </Tooltip>
                          </Grid>
                        </Grid>
                      </form>
                      <Typography variant="overline">#Indicators: {indicatorsSelected.length}</Typography>
                    </Grid>
                  )
                }
              />
            </Grid>
          </Grid>
          <Divider className={classes.divider}/>
          <CardContent style={{backgroundColor: '#fff'}}>
            {codeFetched ? (
                <Grid container direction="column" style={{color: '#000'}} justify="center">
                  <Grid item xs={false} sm={1} lg={0}/>
                  <Grid container justify="center" spacing={3}>
                    {visualizationData.map((vizData, index) => {
                      return (
                        <Grid item key={index} xs={12} sm={10} lg={6}>
                          <VisualizationPreview
                            vizData={vizData}
                            classes={classes}/>
                        </Grid>)
                    })}
                  </Grid>
                  <Grid item xs={false} sm={1} lg={0}/>
                </Grid>
              ) :
              <Grid container direction="column" alignItems="center">
                <CircularProgress className={classes.gutterTopBottom}/>
                <Typography variant="overline" style={{color: "#000"}}>Loading Visualizations</Typography>
              </Grid>}
          </CardContent>
        </Card>
      </Grid>


      <Grid container className={styles.gutter}>

        <Button onClick={handleStepBackward} className={styles.buttonSpacing}> Back </Button>

        <Tooltip arrow disableHoverListener={questionConfirmed} title={
          <Typography >
            Please confirm question
          </Typography>}>
          <Button
            onClick={handleSaving} variant="contained"
            disabled={questionConfirmed && !questionAvailable ||
            !questionConfirmed && !questionAvailable || !questionConfirmed && questionAvailable}
            color="primary"
            startIcon={<SaveIcon/>}>
            Save & Exit
          </Button>
        </Tooltip>
      </Grid>

      <ModalMessage
        dialogTitle={"Your Question and associated Indicators have been saved!"}
        dialogPrimaryContext={`In your Dashboard, you will find the recently created question and indicators.`}
        dialogSecondaryContext={<Typography>
          <b>Shareable links is now available in Dashboard.</b>
        </Typography>}
        openDialog={dashboardModal}
        setOpenDialog={setDashboardModal}
        primaryAction={handleBackToDashboard}
        primaryButton={"back to dashboard"}
      />
      <SnackbarMessage
        message={"This question already exists, please rephrase your question."}
        type={"error"}
        openSnackbar={questionConfirmed && !questionAvailable}
        setOpenSnackbar={setErrorInput}
        duration={3000}
      />
    </>
  )
}
